import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/apis/video.dart';
import 'package:qgchat/http/models/anchorInfoModel.dart';
import 'package:qgchat/http/models/listuserInfoModel.dart';
import 'package:qgchat/http/models/tokenuserInfoModel.dart';
import 'package:qgchat/http/models/userInfoModel.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:qgchat/widgets/Zego/ZegoPreview.dart';
import 'package:zego_express_engine/zego_express_engine.dart';

import 'Bloc/TargetInfoBlocBloc.dart';

class MakeCall extends StatefulWidget {
  final String targetToken;
  final int inv;
  MakeCall({
    @required this.targetToken,
    @required this.inv,
    Key key,
  }) : super(key: key);

  @override
  _MakeCallState createState() => _MakeCallState();
}

class _MakeCallState extends State<MakeCall> {
  StreamSubscription stopCallSub;
  final zegoKey = GlobalKey<ZegoPreviewState>();
  Timer timer;

  @override
  void initState() {
    super.initState();
    // 修改通话状态
    Global.talking.value = true;

    // 30s内未接听挂断电话
    timer = Timer(
      Duration(seconds: 30),
      () {
        if (mounted) {
          toast('长时间未接听，自动挂断');
          Navigator.pop(context);
          Global.talking.value = false;
        }
      },
    );

    // socket - 播打方放弃拨号
    final not = Global.socketNot;
    stopCallSub = not.value
        .map((str) => jsonDecode(str))
        .where((cls) => cls['datatype'] == 'stopinv')
        .listen(
      (res) {
        toast('对方中断拨号');
        Navigator.pop(context);
        Global.talking.value = false;
      },
    );
  }

  @override
  void dispose() {
    timer?.cancel();
    stopCallSub?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<TargetInfoBlocBloc>(
      create: (context) => TargetInfoBlocBloc(
        targetToken: widget.targetToken,
        inv: widget.inv,
      ),
      child: WillPopScope(
        onWillPop: () async => false,
        child: _Ringtone(
          child: Scaffold(
            backgroundColor: Colors.grey,
            body: Stack(
              alignment: Alignment.center,
              children: [
                // Builder(
                //   builder: (context) {
                //     // 计算屏幕像素
                //     final width = MediaQuery.of(context).size.width.toInt();
                //     final height = MediaQuery.of(context).size.height.toInt();
                //     final ratio =
                //         MediaQuery.of(context).devicePixelRatio.toInt();
                //     final screenWidthPx = width * ratio;
                //     final screenHeightPx = height * ratio;
                //     return ZegoPreview(
                //       screenWidthPx: screenWidthPx,
                //       screenHeightPx: screenHeightPx,
                //       key: zegoKey,
                //     );
                //   },
                // ),
                _FilterBlur(),
                _UserInfo(),
                _UserData(),
                _TipsText(),
                _ToolPanel(zegoKey: zegoKey),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 铃声播放
class _Ringtone extends StatefulWidget {
  final Widget child;
  _Ringtone({@required this.child, Key key}) : super(key: key);

  @override
  __RingtoneState createState() => __RingtoneState();
}

class __RingtoneState extends State<_Ringtone> {
  AudioCache audio;
  AudioPlayer player;

  @override
  void initState() {
    super.initState();
    audio = AudioCache(prefix: 'audio/');
    audio.loop("videoCall.mp3").then((value) => player = value);
  }

  @override
  void dispose() {
    player?.stop();
    audio?.clear("videoCall.mp3");
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

// 毛玻璃层
class _FilterBlur extends StatelessWidget {
  const _FilterBlur({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 30, sigmaY: 30),
      child: Container(
        color: Colors.white.withAlpha(0),
      ),
    );
  }
}

// 用户信息
class _UserInfo extends StatelessWidget {
  const _UserInfo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return BlocBuilder<TargetInfoBlocBloc, TokenuserInfoModel>(
      builder: (context, state) {
        if (state.id == null) return Container();

        return Positioned(
          top: top + px(128),
          child: Column(
            children: [
              Container(
                width: px(180),
                height: px(180),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(90),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black12,
                      offset: Offset(0.0, 1),
                      blurRadius: 1,
                      spreadRadius: 1,
                    ),
                  ],
                  image: DecorationImage(
                    fit: BoxFit.cover,
                    image: NetworkImage(
                      state.memberHead,
                    ),
                  ),
                ),
              ),
              SizedBox(height: px(40)),
              Text(
                state.memberNickname,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(38),
                  shadows: [
                    Shadow(
                      color: Colors.black26,
                      blurRadius: 1,
                      offset: Offset(1, 1),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

// 为你消费 和 财富余额
class _UserData extends StatefulWidget {
  _UserData({Key key}) : super(key: key);

  @override
  __UserDataState createState() => __UserDataState();
}

class __UserDataState extends State<_UserData> {
  UserInfoModel userModel;
  AnchorInfoModel anchor;
  ListuserInfoModel user;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final targetToken = context.bloc<TargetInfoBlocBloc>().targetToken;
    userModel = Provide.value<UserState>(context).info;
    if (userModel.memberType == 0) {
      UserApis.topbigVintroduce(targetToken).then((data) {
        anchor = data;
        setState(() {});
      });
    } else {
      VideoApis.listuserInfo(userModel.memberToken, targetToken).then((data) {
        user = data;
        setState(() {});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return Positioned(
      top: top + px(435),
      child: Container(
        width: w100(context),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            if (anchor != null)
              Text(
                "该主播时光价值 ${anchor.timePrice} 香币/分钟",
                style: TextStyle(
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      color: Colors.black26,
                      blurRadius: 1,
                      offset: Offset(1, 1),
                    ),
                  ],
                ),
              ),
            if (user != null)
              _UserDataItem(
                title: '为你消费',
                count: user?.gold1 ?? 0,
              ),
            if (user != null)
              _UserDataItem(
                title: '财富余额',
                count: user?.money ?? 0,
              ),
          ],
        ),
      ),
    );
  }
}

// 用户数据单元
class _UserDataItem extends StatelessWidget {
  final String title;
  final int count;
  const _UserDataItem({
    @required this.title,
    @required this.count,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          Text(
            title,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(28),
              shadows: [
                Shadow(
                  color: Colors.black26,
                  blurRadius: 1,
                  offset: Offset(1, 1),
                ),
              ],
            ),
          ),
          SizedBox(height: px(30)),
          RichText(
            text: TextSpan(
              style: TextStyle(
                color: Colors.white,
                shadows: [
                  Shadow(
                    color: Colors.black26,
                    blurRadius: 1,
                    offset: Offset(1, 1),
                  ),
                ],
              ),
              children: [
                TextSpan(
                  text: '$count',
                  style: TextStyle(fontSize: px(50)),
                ),
                TextSpan(
                  text: '金币',
                  style: TextStyle(fontSize: px(32)),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 提示
class _TipsText extends StatelessWidget {
  const _TipsText({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: px(500),
      child: Text(
        '向你发起视频通话请求',
        style: TextStyle(
          color: Colors.white,
          fontSize: px(26),
          shadows: [
            Shadow(
              color: Colors.black26,
              blurRadius: 1,
              offset: Offset(1, 1),
            ),
          ],
        ),
      ),
    );
  }
}

// 操作按钮
class _ToolPanel extends StatelessWidget {
  final GlobalKey<ZegoPreviewState> zegoKey;
  const _ToolPanel({this.zegoKey, Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: px(180),
      child: Container(
        width: w100(context),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            GestureDetector(
              onTap: () {
                final inv = context.bloc<TargetInfoBlocBloc>().inv;
                Global.ws.refuseVideo(inv);
                Navigator.of(context).pop();
                Global.talking.value = false;
              },
              child: _ToolPanelItem(
                icon: 'oncall',
                title: '拒绝',
              ),
            ),
            GestureDetector(
              onTap: () {
                if (!Global.talking.value) return;

                // zegoKey.currentState.isDispose = false;
                // final textureID = zegoKey.currentState.info.textureID;
                // ZegoExpressEngine.instance.stopPreview().then((value) {
                //   ZegoExpressEngine.instance
                //       .destroyTextureRenderer(textureID)
                //       .then((value) {
                //     final token =
                //         context.bloc<TargetInfoBlocBloc>().targetToken;
                //     final inv = context.bloc<TargetInfoBlocBloc>().inv;
                //     // 接受邀请，返回邀请id
                //     Global.ws.sendInvtokening(inv);

                //     // 进入通话页面
                //     goPage(
                //       context,
                //       '/talk',
                //       param: {'inv': inv, 'token': token},
                //       replace: true,
                //     );
                //   });
                // });

                final token = context.bloc<TargetInfoBlocBloc>().targetToken;
                final inv = context.bloc<TargetInfoBlocBloc>().inv;
                // 接受邀请，返回邀请id
                Global.ws.sendInvtokening(inv);

                // 进入通话页面
                goPage(
                  context,
                  '/talk',
                  param: {'inv': inv, 'token': token},
                  replace: true,
                );
              },
              child: _ToolPanelItem(
                icon: 'notcall',
                title: '接听',
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 操作按钮单元
class _ToolPanelItem extends StatelessWidget {
  final String icon;
  final String title;
  const _ToolPanelItem({
    @required this.icon,
    @required this.title,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Container(
          width: px(150),
          height: px(150),
          child: Image.asset(
            "assets/images/icon/$icon.png",
            fit: BoxFit.cover,
          ),
        ),
        SizedBox(height: px(16)),
        Text(
          title,
          style: TextStyle(
            color: Colors.white,
            fontSize: px(32),
            shadows: [
              Shadow(
                color: Colors.black26,
                blurRadius: 1,
                offset: Offset(1, 1),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
